/*
 *
 *      Copyright (c) 2018-2025, cloud All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: cloud
 *
 */

package com.fuyao.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.admin.api.entity.SysUserRole;
import com.fuyao.cloud.admin.mapper.SysUserRoleMapper;
import com.fuyao.cloud.admin.service.SysUserRoleService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author cloud
 * @since 2017-10-29
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

	/**
	 * 根据用户Id删除该用户的角色关系
	 * @param userId 用户ID
	 * @return boolean
	 * @author 寻欢·李
	 * @date 2017年12月7日 16:31:38
	 */
	@Override
	public Boolean deleteByUserId(Long userId) {
		return baseMapper.deleteByUserId(userId);
	}

	@Override
	public Boolean saveUserRoleInfo(List<SysUserRole> userRoleList) {
		if(CollUtil.isEmpty(userRoleList)){
			return Boolean.FALSE;
		}
		List<SysUserRole> saveUserRoleList = Lists.newArrayList();
		List<Long> roleIds = userRoleList.stream().map(SysUserRole::getRoleId).distinct().collect(Collectors.toList());
		// 先删除
		roleIds.forEach(roleId-> super.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,roleId)));
		// 在添加
		userRoleList.forEach(userRole->{
			LambdaQueryWrapper<SysUserRole> queryWrapper = Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userRole.getUserId()).eq(SysUserRole::getRoleId, userRole.getRoleId());
			if(this.count(queryWrapper) == 0){
				saveUserRoleList.add(userRole);
			}
		});
		return saveBatch(saveUserRoleList);
	}
}
